package com.itheima.service;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SpringSecurityUserService2 implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    public Map<String, User> map = new HashMap<>();

    public void initUserData() {
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));
        User user2 = new User();
        user2.setUsername("xiaoming");
        user2.setPassword(passwordEncoder.encode("1234"));
        map.put(user1.getUsername(), user1);
        map.put(user2.getUsername(), user2);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initUserData();
        System.out.println("用户输入的用户名：" + username);
        //根据用户名查询数据库获得用户信息（数据库中存储的密码信息）
        User user = map.get(username); //模拟查询数据库
        if (user == null) {
            //用户名不存在
            return null;
        }
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        //当前用户权限
        list.add(new SimpleGrantedAuthority("permission_A"));//授予权限
        list.add(new SimpleGrantedAuthority("permission_B")); //授予权限
        if (username.equals("admin")) {
            list.add(new SimpleGrantedAuthority("ROLE_ADMIN")); //授予角色
            list.add(new SimpleGrantedAuthority("add")); //授予角色
        }
        //将用户信息返回给框架
        org.springframework.security.core.userdetails.User securityUser;
        securityUser = new org.springframework.security.core.userdetails.User(username,  user.getPassword(), list);
        //框架会进行密码对比 （页面提交的密码和数据库中查询的密码进行比对）
        return securityUser;
    }
}
